package com.xjoyt.pay.master.core.order;

import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.gateway.params.CallbackParam;
import com.xjoyt.pay.master.core.order.handle.AbstractOrderCallbackHandle;
import com.xjoyt.pay.master.core.order.handle.callback.CallbackHandle;
import com.xjoyt.pay.master.core.order.handle.callback.CheckHandle;
import com.xjoyt.pay.master.core.order.handle.callback.MoneyHandle;
import com.xjoyt.pay.master.core.order.handle.callback.NotifyHandle;
import com.xjoyt.pay.master.core.order.handle.callback.PayHandle;
import com.xjoyt.pay.master.core.order.handle.callback.ProfitHandle;
import com.xjoyt.pay.master.dto.CallbackResult;
import com.xjoyt.pay.master.po.Order;
import com.xjoyt.pay.master.repository.OrderRepository;

/**
 * 订单回调处理
 * 
 * @author Administrator
 *
 */
@Component
public class OrderCallbackHandle {

	@Autowired
	private OrderRepository repository;

	@Autowired
	private CallbackHandle callbackHandle;

	@Autowired
	private MoneyHandle moneyHandle;

	@Autowired
	private ProfitHandle profitHandle;

	@Autowired
	private NotifyHandle notifyHandle;

	@Autowired
	private PayHandle payHandle;

	@Autowired
	private CheckHandle checkHandle;

	private AbstractOrderCallbackHandle startHandle;

	private AbstractOrderCallbackHandle getStartHandle() {
		if (startHandle != null) {
			return startHandle;
		}

		// 回调处理
		callbackHandle.setNext(moneyHandle);
		// 资金处理
		moneyHandle.setNext(profitHandle);
		// 分润处理
		profitHandle.setNext(notifyHandle);
		// 通知处理
		notifyHandle.setNext(payHandle);
		// 代付处理
		payHandle.setNext(checkHandle);

		startHandle = callbackHandle;
		return startHandle;
	}

	public ExecuteResult<CallbackResult> handle(CallbackParam param) throws Exception {
		Order order = repository.findOne(param.id);
		if (order == null || BooleanUtils.isNotTrue(order.success) || order.orderConfig == null
				|| StringUtils.isBlank(order.orderConfig.callbackUrl)) {
			return ExecuteResult.fail("订单失效");
		}
		param.order=order;
		return getStartHandle().handle(param, order);
	}
}
